import swal from 'sweetalert2';
import { Component, ViewChild, OnDestroy, OnInit, AfterViewInit } from '@angular/core';
import { ActivatedRoute, Router, Params } from '@angular/router';
import { TranslateService } from '@ngx-translate/core';

import { User } from '../../../core/auth/user.service';
import { CommonService } from '../../../core/common/common.service';
import { TableDictService } from '../../../core/common/table-dict.service';
import { TagService } from '../../../core/common/tag.service';
import { UserInfoService } from '../service/user-info.service';
import { ECharts } from 'echarts-ng2';
import { Observable } from 'rxjs/Rx';
@Component({
  selector: 'ncloud-userinfo-brand-rank',
  templateUrl: './brandRank.html',
  styleUrls: ['./brandRank.scss']
})
export class UserInfoBrandRank implements OnInit, OnDestroy {
  public bandWidthInfo: Array<any>;
  public view = 0;
  public dates = [];
  public selectedDate: string;
  public usedSelectedDate: string;
  public appData: Array<any>;
  public wuhan_interface_on: Observable<any>;
  public selectedNode: any;
  public custId: string;
  public selectedNodePosition: any = {};
  public destroy = false;
  @ViewChild('bandWidthChart') bandWidthChart: ECharts;
  @ViewChild('bandWidthChartUsed') bandWidthChartUsed: ECharts;
  public bandWidthChartOptionsUsed: any = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      x: 'left',
    },
    series: [
      {
        name: '带宽应用使用情况',
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        label: {
          normal: {
            show: false,
            position: 'center'
          },
          emphasis: {
            show: true,
            textStyle: {
              fontSize: '30',
              fontWeight: 'bold'
            }
          }
        },
        labelLine: {
          normal: {
            show: false
          }
        },
      }
    ]
  };
  public bandWidthChartOptions: any = {
    title: {
      text: '',
      subtext: ''
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['最高', '最低']
    },
    toolbox: {
      show: true,
      feature: {
        dataZoom: {
          yAxisIndex: 'none'
        },
        dataView: { readOnly: false },
        magicType: { type: ['line', 'bar'] },
        restore: {},
        saveAsImage: {}
      }
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '{value}'
      }
    },
    series: [
      {
        name: '最高',
        type: 'line',
        markPoint: {
          data: [
            { type: 'max', name: '最大值' },
            { type: 'min', name: '最小值' }
          ]
        },
        markLine: {
          data: [
            { type: 'average', name: '平均值' }
          ]
        }
      },
    ]
  };

  constructor(private common: CommonService, public user: User, public userInfoService: UserInfoService,
    private route: ActivatedRoute, private router: Router, private tableDict: TableDictService, private translate: TranslateService,
    private tagService: TagService) {
    $(window).resize(() => {
      if (!this.destroy) {
        this.bandWidthChart.resize();
        this.bandWidthChartUsed.resize();
      }
    });
    this.tableDict.get('USERINFO_TIME').subscribe(r => this.dates = r);
    this.userInfoService.getNodeBandWidth().map(res => {
      return res.data;
    }).subscribe((res: any) => {
      this.custId = res.custId;
      this.bandWidthInfo = res.data;
    });
  }
  ngOnInit() {
    this.initParameters();
  }
  ngOnDestroy() {
    this.destroy = true;
  }
  private initParameters(): void {
    this.route.params.switchMap((params: Params) => {
      const result: any = [];
      if (params['data']) {
        this.selectedNode = JSON.parse(params['data']);
      }
      if (params['custId']) {
        this.custId = params['custId'];
      }
      if (this.selectedNode && this.custId && params['fromUserPortal']) {
        this.selectedDate = '15minutesAgo';
        this.usedSelectedDate = '15minutesAgo';
        this.getNodePosition(this.custId, this.selectedNode.devname);
      }
      return result;
    }
    ).subscribe((c: any) => { });
  }
  onRowSelect(event) {
  }
  public getNodeBandWidthUsed(): void {
    if (this.selectedNode && this.selectedDate) {
      this.userInfoService.getNodeBandWidthUsed(this.selectedNode.devname, this.selectedDate).map(res => {
        return res.data;
      }).subscribe((res: any) => {
        if (res.data) {
          if (res.data.length > 0) {
            res.data.forEach((d: any) => this.processBandWidthChartData(d.data));
          } else {
            this.processBandWidthChartData([]);
          }
        }
      });
    }
  }
  public processBandWidthChartData(array): void {
    const xData = [];
    const yData = [];
    array.forEach((t: any) => {
      const d = new Date();
      d.setTime(t[0]);
      xData.push(d.toLocaleString());
      yData.push(t[1]);
    });
    this.bandWidthChartOptions.xAxis.data = xData;
    this.bandWidthChartOptions.series[0].data = yData;
    if (this.bandWidthChart) {
      this.bandWidthChart.setOption(this.bandWidthChartOptions);
      this.bandWidthChart.resize();
    }
  }
  public getAppData(): void {
    if (this.selectedNode && this.usedSelectedDate) {
      this.userInfoService.getAppData(this.selectedNode.devname, this.usedSelectedDate).map(res => {
        return res.data;
      }).subscribe((res: any) => {
        this.appData = res.data;
        this.processAppData();
      });
    }
  }
  public processAppData(): void {
    this.appData.sort((a, b) => { return b.bandwidth - a.bandwidth; });
    const lData = [];
    const sData = [];
    let other = 0;
    for (let i = 0; i < this.appData.length; i++) {
      if (i < 5) {
        lData.push(this.appData[i].appName);
        sData.push({ value: this.appData[i].bandwidth, name: this.appData[i].appName });
      } else {
        if (lData.indexOf('其他') <= -1) {
          lData.push('其他');
        }
        other += this.appData[i].bandwidth;
      }
    }
    sData.push({ value: other, name: '其他' });
    this.bandWidthChartOptionsUsed.legend.data = lData;
    this.bandWidthChartOptionsUsed.series[0].data = sData;
    if (this.bandWidthChartUsed) {
      this.bandWidthChartUsed.setOption(this.bandWidthChartOptionsUsed);
      this.bandWidthChartUsed.resize();
    }
  };
  public viewDetail(node): void {
    this.selectedDate = '15minutesAgo';
    this.usedSelectedDate = '15minutesAgo';
    this.selectedNode = node;
    this.getNodePosition(this.custId, node.devname);
  }
  public getNodePosition(custId, nodeCode): void {
    this.userInfoService.getNodePosition(custId, nodeCode).subscribe((res: any) => {
      this.selectedNodePosition.longtitude = res.lng;
      this.selectedNodePosition.latitude = res.lat;
      this.view = 1;
    });
  }
  back(): void {
    this.view = 0;
    this.selectedDate = null;
    this.usedSelectedDate = null;
  }
}
